import os
train_0_dir="./mfccdata/train/0"
train_1_dir="./mfccdata/train/1"
test_0_dir="./mfccdata/test/0"
test_1_dir="./mfccdata/test/1"
validation_0_dir="./mfccdata/validation/0"
validation_1_dir="./mfccdata/validation/1"
train_dir="./mfccdata/train"
test_dir="./mfccdata/test"
validation_dir="./mfccdata/validation"
#创建模型
from keras import layers
from keras import models
from keras.callbacks import EarlyStopping
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
                        input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
from keras import optimizers

model.compile(loss='binary_crossentropy',
              optimizer=optimizers.RMSprop(lr=1e-4),
              metrics=['acc'])
from keras.preprocessing.image import ImageDataGenerator
# 所有的图像将重新进行归一化处理　Rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1./255)
validation_datagen=ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
# 直接从目录读取图像数据
train_generator = train_datagen.flow_from_directory(
         # 训练图像的目录
        train_dir,
         # 所有图像大小会被转换成150x150
        target_size=(150, 150),
         # 每次产生20个图像的批次
        batch_size=20,
         # 由于这是一个二元分类问题，y的label值也会被转换成二元的标签
        class_mode='binary')
# 直接从目录读取图像数据
validation_generator = test_datagen.flow_from_directory(
        validation_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')
test_generator = test_datagen.flow_from_directory(test_dir,
                                                   target_size=(150, 150),
                                                   batch_size=20,
                                                   class_mode='binary')

for data_batch, labels_batch in train_generator:
    print('data batch shape:', data_batch.shape)
    print('labels batch shape:', labels_batch)
    break
monitor = EarlyStopping(monitor='val_loss', min_delta=1e-4, patience=200, verbose=1, mode='auto')
history = model.fit_generator(
      train_generator,
      callbacks = [monitor],
      steps_per_epoch=6,
      epochs=1500,
      validation_data=validation_generator,
      validation_steps=3)
model.save('./test_6.h5')
result = model.evaluate(test_generator,steps=1)
print('evaluate:')
print(result[1])
